package com.example.springaidemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.Duration;

@RestController
@CrossOrigin(origins = "*")
@Slf4j
public class ChatBoxController {
    private final ChatClient.Builder builder;
    private ChatClient chatClient;
    private String systemPrompt = "你是一个天气预报员，当有人输入日期的时候，你输出洛阳的天气预报信息，生成结果在html页面中以markdown的格式输出，最后输出结尾的时候始终以下面的语句结尾：感谢您的咨询，我是金刚侠客,千年古都,洛阳欢迎您。";

    public ChatBoxController(ChatClient.Builder builder) {
        this.builder = builder;
        this.chatClient = builder.defaultSystem(systemPrompt).build();
    }

    @PostMapping("/updateSystemPrompt")
    public String updateSystemPrompt(@RequestBody String newPrompt) {
        this.systemPrompt = newPrompt;
        this.chatClient = builder.defaultSystem(systemPrompt).build();
        return "系统提示已更新";
    }

    @GetMapping(value = "/chat/{message}")
    public String chat(@PathVariable("message") String message) {
        // 每次调用前重新构建chatClient以确保使用最新的systemPrompt
        this.chatClient = builder.defaultSystem(systemPrompt).build();
        return chatClient.prompt()
                .user(message)
                .call()
                .content();
    }

    @GetMapping(value = "/chat/stream/{message}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@PathVariable("message") String message) {
        return chatClient.prompt()
                .user(message)
                .stream()
                .content()
                .flatMap(content -> Flux.fromArray(content.split("")))
                .bufferTimeout(15, Duration.ofMillis(10))
                .map(buffer -> String.join("", buffer))
                .filter(text -> !text.trim().isEmpty());
    }
}
